package _interview100;

import java.util.Arrays;

/**
 * 73. 矩阵置零
 */
public class No73 {
    /**
     * 1. O(m + n) 的额外空间
     */
    public void setZeroes1(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        boolean[] zeroRow = new boolean[m];
        boolean[] zeroColum = new boolean[n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    zeroRow[i] = true;
                    zeroColum[j] = true;
                }
            }
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (zeroRow[i] || zeroColum[j]) matrix[i][j] = 0;
            }
        }
    }

    /**
     * 2. 原地算法
     */
    public void setZeroes2(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;

        boolean zeroRowFirst = false;
        boolean zeroColumFirst = false;

        for (int j = 0; j < n; j++) {
            if (matrix[0][j] == 0) {
                zeroRowFirst = true;
                break;
            }
        }
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) {
                zeroColumFirst = true;
                break;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    if (i == 0) zeroRowFirst = true;
                    if (j == 0) zeroColumFirst = true;
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[0][j] == 0 || matrix[i][0] == 0) matrix[i][j] = 0;
            }
        }
        if (zeroRowFirst) Arrays.fill(matrix[0], 0);
        if (zeroColumFirst) for (int i = 0; i < m; i++) matrix[i][0] = 0;

    }
}
